package cn.wk.userdetail;

import cn.wk.domain.Permission;
import cn.wk.domain.VipUser;
import cn.wk.mapper.PermissionMapper;
import cn.wk.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MyUserDetail implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从数据中查询用户
        VipUser vipUser = userMapper.selectByUsername(username);
        //准备权限  从数据库中查询
        ArrayList<GrantedAuthority> authorities = new ArrayList<>();
        List<Permission> permissions = permissionMapper.selectPermissionsByUserId(vipUser.getId());
        permissions.forEach(permission -> {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(permission.getExpression());
            authorities.add(simpleGrantedAuthority);
        });
        User user = new User(vipUser.getVipUsername(), vipUser.getPassword(), vipUser.isEnabled()
                , vipUser.isAccountNonExpired(), vipUser.isCredentialsNonExpired()
                , vipUser.isAccountNonLocked(), authorities);
        return user;
    }
}
